import { getDicByKey } from '@/support/common';
import { Card, message } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import * as G from '../../../utils/common';
import { getMd5 } from '@/utils/utils';
import { fingerprintFetch } from '@/utils/request';

const mapStateToProps = (state: any) => ({
  ipdaLog: state.ipdaLog,
  loading: state.loading.effects['ipdaLog/postFetchPage'],
});
class IpdaLog extends PureComponent<any, any> {
  static contextTypes = {
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      projectOptions: [],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipdaLog/postFetchPage',
      payload: { url: '/userfeedback/ipdalogfindbypage' },
    });

    dispatch({
      type: 'ipdaLog/getDataWithRes',
      payload: { url: '/basedata/findprojectbylogin' },
      callback: (data: any) => {
        if (data) {
          this.setState({
            projectOptions: data,
          });
        }
      },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipdaLog/initData',
    });
  }

  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['createDateRange'])) {
      const [start, end] = fields.createDateRange;
      // fields['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
      fields['startTime'] = G.startDayFormat(start);
      // fields['endTime'] = moment(end).format('YYYY-MM-DD HH:mm:ss');
      fields['endTime'] = G.endDayFormat(end);
      delete fields['createDateRange'];
      return fields;
    } else {
      delete fields['startTime'];
      delete fields['endTime'];
      delete fields['createDateRange'];
      return fields;
    }
  };

  handleDownload = (strUrl: any, name: any) => {
    if (strUrl === null || strUrl === '') {
      message.error('日志文件缺失或格式不正确，无法下载！');
      return;
    }

    const fileName = strUrl.split('/')[strUrl.split('/').length - 1].split('.')[1];
    name = `${name}.${fileName}`;
    const str = `${window.g.url}/common/download?strUrl=` + strUrl;
    let md5 = getMd5('strUrl=' + strUrl);
    const newOptions: any = {};
    newOptions.method = 'GET';
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display = 'none';
        aLink.href = window.URL.createObjectURL(blob);
        aLink.download = name;
        aLink.click();
        document.body.removeChild(aLink);
      })
      .catch(() => message.error('下载失败，请稍后在试!'));
  };

  render() {
    const {
      ipdaLog: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { projectOptions } = this.state;
    const { formValues } = this.state;
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: 'PDSN',
        dataIndex: 'pdsn',
      },
      {
        title: '日志类型',
        dataIndex: 'messageType',
        render: (text: any) => {
          if (text != null && text != undefined) {
            return getDicByKey(this.context.dicData, `ipdaLogMessageType`, text + '');
          } else {
            return text;
          }
        },
      },
      {
        title: '日志名称',
        dataIndex: 'fileName',
        render: (text: any) => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '问题编码',
        dataIndex: 'infoId',
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
      },
      {
        title: '日志文件',
        dataIndex: 'hasLog',
        render: (text: any, record: any) => {
          return record?.fileName ? '有' : '无';
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 60,
        fixed: 'right',
        render: (text: any, record: any) => {
          let btns = [];
          if (record?.fileName) {
            btns.push({
              title: '下载',
              key: 'download',
              auth: 'ipdaLog_doDownload',
              Popconfirm: true,
              message: '是否确认下载？',
              onConfirm: () => {
                if (
                  record.deflautFile !== null &&
                  record.deflautFile !== '' &&
                  (record.deflautFile.endsWith('.tar.gz') || record.deflautFile.endsWith('.gz'))
                ) {
                  window.location.href = record.deflautFile;
                } else {
                  this.handleDownload(record.deflautFile, record.fileName);
                }
              },
            });
          }
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'select',
        title: '所属项目',
        key: 'projectId',
        selectOptions: projectOptions,
        keyValue: ['value', 'label'],
      },
      {
        type: 'input',
        title: 'PDSN',
        key: 'pdsn',
      },
      {
        type: 'input',
        title: 'VIN',
        key: 'vin',
      },
      {
        type: 'input',
        title: '问题编码',
        key: 'infoId',
        customStyle: 6,
      },
      {
        type: 'rangePicker',
        title: '创建时间1',
        key: 'createDateRange',
        showTime: false,
        format: 'YYYY-MM-DD',
        customStyle: 10,
      },
      {
        type: 'select',
        title: '是否有日志文件',
        key: 'hasLog',
        initialValue: '2',
        selectOptions: [
          { value: '2', label: '默认（全部）' },
          { value: '1', label: '有' },
          { value: '0', label: '无' },
        ],
        keyValue: ['value', 'label'],
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'ipdaLog/postFetchPage', url: '/userfeedback/ipdalogfindbypage' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'ipdaLog/postFetchPage', url: '/userfeedback/ipdalogfindbypage' }}
            formValues={formValues}
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(IpdaLog);
